var app = getApp();
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
var WxParse = require('../wxParse/wxParse.js');

Page({
  data: {
    hiddenName: true,
    tuangouId: '',
    givePoint: '',
    values: [],
    selectedProductStockId: '',
    cartCounts: 0,
    swiperpics: [],
    product: null,
    productStock: null,
    couponTypeList: [],
    isSell: false,
    sellDate: '',
    isSpec: 0,
    specNameValue: [],
    productStockId: '',
    countDownDay: 0,//倒计时 天数
    countDownHour: 0,//倒计时 时
    countDownMinute: 0,//分
    countDownSecond: 0,//秒
    id: 0,
    goods: {},
    gallery: [],
    attribute: [{
      name:'颜色',
      value:'黄色、粉色、黑色'
    },{
      name:'面料',
      value:'纯棉'
    },{
      name:'清洗方式',
      value:'手洗、机洗'
    }],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    openCoupons:false,
    boxShow: false,
    noCollectImage: "/static/images/icon_collect.png",
    hasCollectImage: "/static/images/icon_collect_checked.png",
    collectBackImage: "/static/images/icon_collect.png"
  },
  onLoad: function (options) {
    var assembleItemId = options.assembleItemId;
    this.setData({
      productStockId: options.productStockId,
      assembleId: options.assembleId,
      assembleItemId: assembleItemId
    });
    var isTest = app.globalData.isTest;
    if (isTest == 1) {
      this.getProductDetail();
      this.getAssess();
      if (assembleItemId != null && assembleItemId != '') {
        this.getAssembleItemDetail();
      }
    } else {
      user.checkLogin(this);
    }
  },
  bindGetUserInfo: function (e) {
    user.loginByWeixin(e, this);
  },
  getAssembleItemDetail: function () {
    var that = this;
    var data = {
      assembleItemId: that.data.assembleItemId
    }
    util.request(api.AssembleItemDetail, data, 'POST').then(function (data) {
      if (data.type == 'success') {
        that.setData({
          assembleItemMemberList: data.data.assembleItemMemberList,
          lastNum: data.data.lastNum
        });
      } else {
        console.log(data.content);
      }
    });
  },
  //倒计时
  cutDown: function (lastSecond) {
    var totalSecond = lastSecond;

    var interval = setInterval(function () {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        util.showErrorToast('拼团已结束');
        var assembleMemo = this.data.assembleMemo;
        assembleMemo.memo = '拼团已结束'
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          assembleMemo: assembleMemo
        });
      }
    }.bind(this), 1000);
  },
  //领取优惠券
  getCoupon: function (e) {
    var couponTypeId = e.currentTarget.dataset.couponTypeId;
    var data = {
      couponTypeId: couponTypeId
    }
    util.request(api.CouponReceive, data, 'POST').then(function (data) {
      if (data.type == 'success') {
        util.showSuccessToast(data.content);
      } else {
        util.showErrorToast(data.content);
      }
    });
  },
  //减少数量
  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  //增加数量
  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },
  //打开选择优惠券弹窗
  selectCoupons: function () {
    this.setData({
      openCoupons: true, 
      boxShow: true,
    });
  },
  //关闭选择优惠券弹窗
  closeSelectCoupons: function () {
    this.setData({
      openCoupons: false,
      boxShow: false,
    });
  },
  //获取商品详情
  getProductDetail: function () {
    var that = this;
    var data = {
      productStockId: this.data.productStockId,
      assembleId: this.data.assembleId
    }
    util.request(api.AssembleProductDetail, data, 'get').then(function (data) {
      if (data.type === 'success') {  
        var lastSecond = data.data.lastSecond;
        if (lastSecond != null) {
          that.cutDown(lastSecond);
        }
        that.setData({
          swiperpics: data.data.swiperpics,
          product: data.data.product,
          productStock: data.data.productStock,
          couponTypeList: data.data.couponTypeList,
          isSell: data.data.isSell,
          sellDate: data.data.sellDate,
          isSpec: data.data.isSpec,
          specNameValue: data.data.specNameValue,
          price: data.data.price,
          assemblePrice: data.data.assemblePrice,
          shippingFee: data.data.shippingFee,
          assembleMemo: data.data.assembleMemo
        });
        WxParse.wxParse('content', 'html', data.data.product.content, that, 0);
      } else {
        console.log(data.data.content);
      }
    });
  },
  //查看全部评价
  viewAll: function () {
    var productStockId = this.data.productStockId;
    wx.navigateTo({
      url: '/pages/comment/comment?productStockId=' + productStockId,
    })
  },
  //获取第一条评价
  getAssess: function () {
    var that = this;
    var data = {
      productStockId: this.data.productStockId
    }
    util.request(api.PinglunFirst, data, 'POST').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          assess: data.data.assess,
          assessImgList: data.data.assessImgList,
          assessCounts: data.data.assessCounts,
          assessName: data.data.assessName,
          assessAvatar: data.data.assessAvatar,
          assessTime: data.data.assessTime
        });
      } else {
        console.log(data.content);
      }
    });
  },
  //参与拼团
  joinPintuan: function () {
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
      util.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isImprove = data.data.isImprove;
          if (isImprove == 0) {
            wx.navigateTo({
              url: '/pages/ucenter/improveinfo/improveinfo',
            })
          } else {
            var memo = that.data.assembleMemo;
            if (memo != '拼团进行中') {
              util.showErrorToast(memo);
              return false;
            }
            var productStockId;
            if (that.data.isSpec == 0) {
              productStockId = that.data.productStockId
            } else {
              if (!that.isCheckedAllSpec()) {
                util.showErrorToast('请选择完整规格');
                return false;
              }
              productStockId = that.data.selectedProductStockId
            }
            var assembleId = that.data.assembleId;
            var quantity = that.data.number;
            var price = that.data.assemblePrice;
            var imgUrl = that.data.product.showUrl;
            var name = that.data.product.name;
            var subName = that.data.product.subname;
            var specName = that.data.productStock.specName;
            var memo = that.data.product.memo;
            var assembleItemId = that.data.assembleItemId;
						var isPointPay = that.data.product.isPointPay;
            var tuanType = 1;
            wx.navigateTo({
							url: '/pages/shopping/checkoutPintuan/checkoutPintuan?productStockId=' + productStockId + '&quantity=' + quantity + '&price=' + price + '&imgUrl=' + imgUrl + '&name=' + name + '&subName=' + subName + '&specName=' + specName + '&memo=' + memo + '&assembleId=' + assembleId + '&assembleItemId=' + assembleItemId + '&tuanType=' + tuanType + '&isPointPay=' + isPointPay
            })
          }
        }
      });
    }
  },
  //发起拼团
  toPintuan: function () {
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
      util.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isImprove = data.data.isImprove;
          if (isImprove == 0) {
            wx.navigateTo({
              url: '/pages/ucenter/improveinfo/improveinfo',
            })
          } else {
            var memo = that.data.assembleMemo;
            if (memo != '拼团进行中') {
              util.showErrorToast(memo);
              return false;
            }
            var productStockId;
            if (that.data.isSpec == 0) {
              productStockId = that.data.productStockId
            } else {
              if (!that.isCheckedAllSpec()) {
                util.showErrorToast('请选择完整规格');
                return false;
              }
              productStockId = that.data.selectedProductStockId
            }
            var assembleId = that.data.assembleId;
            var quantity = that.data.number;
            var price = that.data.assemblePrice;
            var imgUrl = that.data.product.showUrl;
            var name = that.data.product.name;
            var subName = that.data.product.subname;
            var specName = that.data.productStock.specName;
            var memo = that.data.product.memo;
						var isPointPay = that.data.product.isPointPay;
            var tuanType = 0;
            wx.navigateTo({
							url: '/pages/shopping/checkoutPintuan/checkoutPintuan?productStockId=' + productStockId + '&quantity=' + quantity + '&price=' + price + '&imgUrl=' + imgUrl + '&name=' + name + '&subName=' + subName + '&specName=' + specName + '&memo=' + memo + '&assembleId=' + assembleId + '&tuanType=' + tuanType + '&isPointPay=' + isPointPay
            })
          }
        }
      });
    }
  },
  //跳转至购物车界面
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    });
  },
  toPointBuy: function () {
    var that = this;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
      util.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isImprove = data.data.isImprove;
          if (isImprove == 0) {
            wx.navigateTo({
              url: '/pages/ucenter/improveinfo/improveinfo',
            })
          } else {
            var productStockId;
            if (that.data.isSpec == 0) {
              productStockId = that.data.productStockId
            } else {
              if (!that.isCheckedAllSpec()) {
                util.showErrorToast('请选择完整规格');
                return false;
              }
              productStockId = that.data.selectedProductStockId
            }
            var quantity = that.data.number;
            var price = that.data.productStock.price;
            var point = that.data.point;
            var imgUrl = that.data.product.showUrl;
            var name = that.data.product.name;
            var subName = that.data.product.subname;
            var specName = that.data.productStock.specName;
            var memo = that.data.product.memo;
            wx.navigateTo({
              url: '/pages/shopping/checkoutPoint/checkoutPoint?productStockId=' + productStockId + '&quantity=' + quantity + '&price=' + price + '&imgUrl=' + imgUrl + '&name=' + name + '&subName=' + subName + '&specName=' + specName + '&memo=' + memo + '&point=' + point
            })
          }
        }
      });
    }
  },
  //添加商品到购物车（直接购买时并跳转）
  addToCart: function (event) {
    var that = this;
    var clickType = event.currentTarget.dataset.nameId;
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    } else {
      util.request(api.CheckImproveUrl, {}, 'POST').then(function (data) {
        if (data.type == 'success') {
          var isImprove = data.data.isImprove;
          if (isImprove == 0) {
            wx.navigateTo({
              url: '/pages/ucenter/improveinfo/improveinfo',
            })
          } else {
            if (that.data.isSpec == 0) {
              //添加到购物车
              var data = {
                productStockId: that.data.productStockId,
                quantity: that.data.number
              }
              util.request(api.CartAdd, data, "POST").then(function (data) {
                if (data.type == 'success') {
                  // setTimeout(function () {
                  if (clickType == 'addToCart') {
                    util.showSuccessToast('添加成功');

                    that.setData({
                      openAttr: !that.data.openAttr,
                      boxShow: !that.data.boxShow,
                      cartCounts: data.data.cartCounts
                    });
                  } else if (clickType == 'addToCartBuy') {
                    wx.switchTab({
                      url: '/pages/cart/cart',
                    });
                  }
                  // }, 1500)
                } else {
                  util.showErrorToast(data.content);
                }
              });
            } else {
              if (!that.isCheckedAllSpec()) {
                util.showErrorToast('请选择完整规格');
                return false;
              }
              var data = {
                productStockId: that.data.selectedProductStockId,
                quantity: that.data.number
              }
              util.request(api.CartAdd, data, "POST").then(function (data) {
                if (data.type == 'success') {
                  // setTimeout(function () {
                  if (clickType == 'addToCart') {
                    util.showSuccessToast('添加成功');

                    that.setData({
                      openAttr: !that.data.openAttr,
                      boxShow: !that.data.boxShow,
                      cartCounts: data.data.cartCounts
                    });
                  } else if (clickType == 'addToCartBuy') {
                    wx.switchTab({
                      url: '/pages/cart/cart',
                    });
                  }
                  // }, 1500)
                } else {
                  util.showErrorToast(data.content);
                }
              });
            }
          }
        }
      });
    }
  },
  //选择规格
  switchAttrPop: function () {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        boxShow: !this.data.boxShow,
        collectBackImage: "/static/images/clear_input.png"
      });
    }
  },
  closeAttrOrCollect: function () {
    let that = this;
    if (this.data.openAttr) {
      this.setData({
        openAttr: false,
        boxShow: false,
      });
      if (that.data.userHasCollect == 1) {
        that.setData({
          'collectBackImage': that.data.hasCollectImage
        });
      } else {
        that.setData({
          'collectBackImage': that.data.noCollectImage
        });
      }
    } else {
      //添加或是取消收藏
      util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.id }, "POST")
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            if ( _res.data.type == 'add') {
              that.setData({
                'collectBackImage': that.data.hasCollectImage
              });
            } else {
              that.setData({
                'collectBackImage': that.data.noCollectImage
              });
            }

          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
    }
  },
  //规格值选择事件
  clickSkuValue: function (event) {
    let that = this;
    let specNameValue = that.data.specNameValue;
    let specNameId = event.currentTarget.dataset.nameId;
    let specValueId = event.currentTarget.dataset.valueId;
    let specNameIndex = event.currentTarget.dataset.nameIndex;
    let specValueIndex = event.currentTarget.dataset.valueIndex;
    for (let i = 0; i < specNameValue[specNameIndex].specValue.length; i++) {
      specNameValue[specNameIndex].specValue[i].selected = false;
    }
    specNameValue[specNameIndex].specValue[specValueIndex].selected = true;
    this.setData({
      specNameValue: specNameValue
    });
    var isSelected = this.isCheckedAllSpec();
    if (isSelected) {
      var data = {
        values: this.data.values,
        productId: this.data.product.id,
        assembleId: this.data.assembleId
      }
      util.request(api.AssembleProductStockId, data, 'POST').then(function (data) {
        if (data.type == 'success') {
          that.setData({
            selectedProductStockId: data.data.productStockId,
            givePoint: data.data.givePoint,
            price: data.data.price,
            productStock: data.data.productStock,
            assemblePrice: data.data.assemblePrice
          })
        }
      });
    }
  },
  //判断是否选择完所有规格，获取所有已选择规格值
  isCheckedAllSpec: function () {
    let specNameValue = this.data.specNameValue;
    let index = 0;
    let values = [];
    for (let i = 0; i < specNameValue.length; i++) {
      for (let j = 0; j < specNameValue[i].specValue.length; j++) {
        let isSelected = specNameValue[i].specValue[j].selected;
        if (isSelected) {
          index ++;
          values.push(specNameValue[i].specValue[j].value);
        }
      }
    }
    this.setData({
      values: values
    });
    return index == specNameValue.length;
  }

})